package com.feicheng.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jakarta.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.feicheng.common.util.StringGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.message.SystemMessage;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Permission;
import com.feicheng.persistence.entity.Role;
import com.feicheng.persistence.entity.User;
import com.feicheng.persistence.model.PermissionModel;
import com.feicheng.persistence.service.IPermissionService;
import com.feicheng.persistence.service.IRoleService;
import com.feicheng.service.IFSystemService;

/**
 * 管理平台系统业务逻辑
 *
 * @see IFSystemService
 */
@Service("system-admin-service")
public class FAdminSystemServiceImpl implements IFSystemService {

	@Autowired
	IRoleService iRoleService;

	@Autowired
	IPermissionService iPermissionService;

	@Autowired
	HttpSession session;

	@Autowired
	SystemMessage systemMessage;

	/**
	 * @see IFSystemService 王兆玉
	 */
	@Override
	public ResultInfo selectRoles(String name, Boolean aFlg, Integer currentPage, Integer pageSize) {
		QueryWrapper<Role> roleQueryWapper = new QueryWrapper<Role>();

		if (StringUtils.hasLength(name)) {
			roleQueryWapper.like(Constant.ENTITY.ROLE.NAME, name);
		}

		if (aFlg != null) {
			roleQueryWapper.eq(Constant.ENTITY.ROLE.A_FLG, aFlg);
		}

		IPage<Role> pageInfo = new Page<Role>(currentPage, pageSize);
		return ResultInfo.success(iRoleService.page(pageInfo, roleQueryWapper));
	}

	/**
	 * @see IFSystemService#allRoles(Boolean) 王兆玉
	 */
	@Override
	public ResultInfo allRoles(Boolean aFlg) {
		QueryWrapper<Role> roleQueryWapper = new QueryWrapper<Role>();
		roleQueryWapper.eq(Constant.ENTITY.ROLE.A_FLG, aFlg);
		return ResultInfo.success(iRoleService.list(roleQueryWapper));
	}

	/**
	 * @see IFSystemService#getRoleById(String) 王兆玉
	 */
	@Override
	public ResultInfo getRoleById(String roleCode) {
		if (!StringUtils.hasLength(roleCode)) {
			throw new SystemException(systemMessage.getE04());
		}

		Role role = iRoleService.getById(roleCode);

		if (null == role) {
			throw new SystemException(systemMessage.getE07());
		}

		JSONObject result = new JSONObject();
		result.put(Constant.RESULT.ROLE.ROLE, role);

		return ResultInfo.success(result);
	}

	/**
	 * @see IFSystemService#addRole(Role) 王兆玉
	 */
	@Override
	public ResultInfo addRole(Role role) {
		if (!StringUtils.hasLength(role.getRoleCode())) {
			throw new SystemException(systemMessage.getE05());
		}


		iRoleService.save(role);

		return ResultInfo.success();
	}

	/**
	 * @see IFSystemService#updateRole(Role) 王兆玉
	 */
	@Override
	public ResultInfo updateRole(Role role) {
		if (!StringUtils.hasLength(role.getRoleCode())) {
			throw new SystemException(systemMessage.getE04());
		}

		iRoleService.updateById(role);

		return ResultInfo.success();
	}

	/**
	 * @see IFSystemService#deleteRole(String) 王兆玉
	 */
	@Override
	public ResultInfo deleteRole(String roleCode) {
		if (!StringUtils.hasLength(roleCode)) {
			throw new SystemException(systemMessage.getE04());
		}
		return ResultInfo.success();
	}

	/**
	 * @see IFSystemService#getPermissions(String, String, Boolean, String, Integer,
	 *      Integer)
	 */
	@Override
	public ResultInfo getPermissions(String name, String path, Boolean aFlg, String pCode, Integer currentPage,
									 Integer pageSize) {
		QueryWrapper<Permission> permissionQueryWapper = new QueryWrapper<Permission>();

		if (StringUtils.hasLength(name)) {
			permissionQueryWapper.like(Constant.ENTITY.PERMISSION.NAME, name);
		}

		if (StringUtils.hasLength(path)) {
			permissionQueryWapper.like(Constant.ENTITY.PERMISSION.PATH, path);
		}

		if (null != aFlg) {
			permissionQueryWapper.eq(Constant.ENTITY.PERMISSION.A_FLG, aFlg);
		}

		if (null != pCode) {
			permissionQueryWapper.eq(Constant.ENTITY.PERMISSION.P_CODE, pCode);
		}
		permissionQueryWapper.orderByAsc("sort");
		IPage<Permission> pageInfo = new Page<Permission>(currentPage, pageSize);
		return ResultInfo.success(iPermissionService.page(pageInfo, permissionQueryWapper));
	}

	/**
	 * @see IFSystemService#allPermissions(Boolean, String) 沈连运
	 */
	@Override
	@Transactional
	public ResultInfo allPermissions(Boolean aFlg, String pCode) {

		if (!StringUtils.hasLength(pCode)) {
			pCode = "0";
		}

		// 创建查询条件
		QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
		if (null != aFlg) {
			permissionQueryWrapper.eq(Constant.ENTITY.PERMISSION.A_FLG, aFlg);
		}

		if (StringUtils.hasLength(pCode)) {
			permissionQueryWrapper.eq(Constant.ENTITY.PERMISSION.P_CODE, pCode);
		}

		permissionQueryWrapper.orderByAsc("sort");

		List<Permission> permissionList = iPermissionService.list(permissionQueryWrapper);
		if (0 == permissionList.size()) {
			throw new SystemException("无可用权限");
		}

		JSONArray ids = new JSONArray();
		permissionQueryWrapper.clear();
		permissionQueryWrapper.and(wp -> {
			for (Permission permission : permissionList) {
				ids.add(permission.getCode());
				String sort = String.valueOf(permission.getSort());
				wp.or().likeRight("sort", StringGenerator.trimRight(sort, "0"));
			}

		});

		if (null != aFlg) {
			permissionQueryWrapper.and(wp -> {
				wp.eq(Constant.ENTITY.PERMISSION.A_FLG, aFlg);
			});

		}

		if (ids.size() > 0) {
			permissionQueryWrapper.and(wp -> {
				wp.notIn("code", ids);
			});

		}

		List<Permission> subList = iPermissionService.list(permissionQueryWrapper);
		permissionList.addAll(subList);

		// 创建map集合用于存放model类型的数据
		Map<String, PermissionModel> permissionMap = new HashMap<>();
		for (Permission permission : permissionList) {
			PermissionModel model = new PermissionModel();
			model.setAFlg(permission.getAFlg());
			model.setCode(permission.getCode());
			model.setIcon(permission.getIcon());
			model.setMFlg(permission.getMFlg());
			model.setName(permission.getName());
			model.setPath(permission.getPath());
			model.setPCode(permission.getPCode());
			model.setSort(permission.getSort());
			model.setType(permission.getType());
			model.setPermissions(new ArrayList<PermissionModel>());
			permissionMap.put(permission.getCode(), model);
		}
		// 创建一个model类型的List集合用于存放最外层权限
		List<PermissionModel> permissionArray = new ArrayList<>();

		for (Permission permission : permissionList) {
			if (pCode.equals(permission.getPCode())) {
				permissionArray.add(permissionMap.get(permission.getCode()));
				continue;
			}
			PermissionModel permissionP = permissionMap.get(permission.getPCode());
			permissionP.getPermissions().add(permissionMap.get(permission.getCode()));
		}

		return ResultInfo.success(permissionArray);
	}

	/**
	 * @see IFSystemService#getPermission(String)
	 */
	@Override
	@Transactional
	public ResultInfo getPermission(String code) {
		if (!StringUtils.hasLength(code)) {
			throw new SystemException(systemMessage.getE08());
		}

		List<Permission> list = iPermissionService.query().eq("code", code)
				.select("code", "name", "path", "a_flg", "type", "m_flg", "p_code").list();

		if (0 == list.size()) {
			throw new SystemException("2");
		}

		return ResultInfo.success(list);
	}

	/**
	 * @see IFSystemService#addPermission(Permission) 唐伟淇
	 */
	@Override
	public ResultInfo addPermission(Permission permission) {

		if (null == permission) {
			// permission对象为空
			throw new SystemException("1");
		}

		if (!StringUtils.hasLength(permission.getCode())) {
			// permission对象的code值为空
			throw new SystemException("2");
		}

		if (!StringUtils.hasLength(permission.getName())) {
			// permission对象的name值为空
			throw new SystemException("4");
		}

		if (!StringUtils.hasLength(permission.getType())) {
			// permission对象的Type值为空
			throw new SystemException("5");
		}

		if (!StringUtils.hasLength(permission.getPCode())) {
			// permission对象的PCode值为空
			throw new SystemException("6");
		}



		// 新增时加锁并且校验一下
		synchronized (this) {
			QueryWrapper queryWrapper = new QueryWrapper<Permission>();
			queryWrapper.eq(Constant.ENTITY.PERMISSION.CODE, permission.getCode());
			long permissionCountByPermissionCode = iPermissionService.count(queryWrapper);
			if (0 < permissionCountByPermissionCode) {
				// permission的code名已经有了
				throw new SystemException("3");
			}

			if ("0".equals(permission.getPCode())) {
				queryWrapper.clear();
				queryWrapper.eq("p_code", permission.getPCode());
				queryWrapper.orderByAsc("sort");
				List<Permission> bothers = iPermissionService.list(queryWrapper);
				if (null == bothers || bothers.size() == 0) {
					permission.setSort(100000);
				} else {
					String maxSort = String.valueOf(bothers.get(bothers.size()-1).getSort());
					maxSort = maxSort.replaceAll("0", "");

					Integer sort = Integer.valueOf(maxSort) + 1;
					String str = String.valueOf(sort);
					str = StringGenerator.addRight(str, "0", (6 - str.length()));
					permission.setSort(Integer.valueOf(str));
				}

			} else {
				queryWrapper.clear();
				queryWrapper.eq("p_code", permission.getPCode());
				queryWrapper.orderByAsc("sort");

				List<Permission> bothers = iPermissionService.list(queryWrapper);

				if (null == bothers || bothers.size() == 0) {
					Permission facherPermission = iPermissionService.getById(permission.getPCode());
					String str = String.valueOf(facherPermission.getSort());
					str = str.replaceAll("0", "");
					str += "1";
					str = StringGenerator.addRight(str, "0", (6 - str.length()));
					permission.setSort(Integer.valueOf(str));
				} else {
					String maxSort = String.valueOf(bothers.get(bothers.size()-1).getSort());
					maxSort = maxSort.replaceAll("0", "");

					Integer sort = Integer.valueOf(maxSort) + 1;
					String str = String.valueOf(sort);
					str = StringGenerator.addRight(str, "0", (6 - str.length()));
					permission.setSort(Integer.valueOf(str));
				}
			}

			iPermissionService.save(permission);
		}

		return ResultInfo.success();
	}

	/**
	 * @see IFSystemService#updatePermission(Permission) 唐伟淇
	 */
	@Override
	public ResultInfo updatePermission(Permission permission) {
		if (null == permission) {
			// permission对象为空
			throw new SystemException("1");
		}

		if (!StringUtils.hasLength(permission.getCode())) {
			// permission对象的code值为空
			throw new SystemException("2");
		}

		QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();

		if (!StringUtils.hasLength(permission.getName())) {
			// permission对象的name值为空
			throw new SystemException("4");
		}

		if (!StringUtils.hasLength(permission.getType())) {
			// permission对象的Type值为空
			throw new SystemException("5");
		}

		if (!StringUtils.hasLength(permission.getPCode())) {
			// permission对象的PCode值为空
			throw new SystemException("6");
		}

		if ("0".equals(permission.getPCode())) {
			// 权限类型属于菜单
			queryWrapper = new QueryWrapper<Permission>();
			queryWrapper.orderByDesc(Constant.ENTITY.PERMISSION.SORT);
			queryWrapper.last("LIMIT 1");
			List<Permission> Permissionlist = iPermissionService.list(queryWrapper);

			if (1 != Permissionlist.size()) {
				// 数据库查不到Permission数据
				throw new SystemException("7");
			}

			Integer sort = (Permissionlist.remove(0).getSort() / 100000 + 1) * 100000;
			permission.setSort(sort);
		} else {
			// 权限类型不属于菜单
			// 查询出所有的permission集合
			List<Permission> PermissionList = iPermissionService.list();

			// 做计数,/用的
			Integer count = 0;

			// 一个用来操作的permission对象 首先赋值为刚开始传的
			Permission usePermission = permission;

			// 用来存储sort的集合
			List<Integer> sortList = new ArrayList<Integer>();

			// 遍历permission集合
			for (Permission sPermission : PermissionList) {

				// 如果有上一级permission,count++并且将操作的permission对象赋值为上一级permission
				if (sPermission.getCode().equals(usePermission.getPCode())) {
					usePermission = sPermission;
					sortList.add(usePermission.getSort());
					count++;
				}

				// 如果操作的permission对象没有上一级结束
				if ("0".equals(usePermission.getPCode())) {
					break;
				}
			}
			Integer number = 1;
			for (int index = 1; index < 6 - count; index++) {
				number = number * 10;
			}
			Integer useSort = sortList.get(0);
			sortList.clear();
			for (Permission sPermission : PermissionList) {
				sortList.add(sPermission.getSort());
			}

			Integer maxSort = 0;
			for (int index = 0; index < sortList.size(); index++) {
				if (sortList.get(index) / number > useSort / number
						&& sortList.get(index) / number < useSort / number + 10) {
					maxSort = sortList.get(index) > maxSort ? sortList.get(index) : maxSort;
				}
			}
			permission.setSort((maxSort / number + 1) * number);
		}

		// 修改时加锁并且校验一下
		synchronized (permission.getCode().intern()) {
			UpdateWrapper<Permission> updateWrapper = new UpdateWrapper<Permission>();
			updateWrapper.eq(Constant.ENTITY.PERMISSION.CODE, permission.getCode());
			iPermissionService.update(permission, updateWrapper);
		}

		return ResultInfo.success();
	}

	/**
	 * @see IFSystemService#deletePermission(String) 唐伟淇
	 */
	@Override
	public ResultInfo deletePermission(String code) {
		QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
		queryWrapper.eq(Constant.ENTITY.PERMISSION.CODE, code);

		long countPermissionByCode = iPermissionService.count(queryWrapper);

		if (1 != countPermissionByCode) {
			// 要删除的数据有说法
			throw new SystemException("7");
		}

		synchronized (code.intern()) {
			countPermissionByCode = iPermissionService.count(queryWrapper);
			if (1 != countPermissionByCode) {
				// 要删除的数据有说法
				throw new SystemException("7");
			}
			iPermissionService.removeById(code);
		}

		return ResultInfo.success();
	}

}
